package nio;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author huyong
 * @version 1.0.0
 * @description
 * @date 2015/5/29 17:36
 */
public class NIOServer extends Thread{
	private InetSocketAddress inetSocketAddress;
	private Handler handler = new ServerHandler();

	public NIOServer(String host, int port){
		inetSocketAddress = new InetSocketAddress(host, port);
	}

	@Override
	public void run(){
		try{
			Selector selector = Selector.open();
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			serverSocketChannel.socket().bind(inetSocketAddress);
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

			System.out.println("Server: socket server started.");
			while (true){
				int nKeys = selector.select();
				if(nKeys>0){
					Set<SelectionKey> selectionKeys = selector.selectedKeys();
					Iterator<SelectionKey> it = selectionKeys.iterator();
					while (it.hasNext()){
						SelectionKey key = it.next();
						if(key.isAcceptable()) {
							System.out.println("Server: SelectionKey is acceptable.");
							handler.handleAccept(key);
						} else if(key.isReadable()) {
							System.out.println("Server: SelectionKey is readable.");
							handler.handleRead(key);
						} else if(key.isWritable()) {
							System.out.println("Server: SelectionKey is writable.");
							handler.handleWrite(key);
						}
						it.remove();
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		NIOServer server = new NIOServer("localhost", 9999);
		server.start();
	}
}

